package bos.dao.base.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import bos.dao.base.IBaseDao;
import bos.utils.PageBean;

public class BaseDaoImpl<T>extends HibernateDaoSupport implements IBaseDao<T>{
	private Class<T> entityClass;
	@Resource
	public void setMySessionFactory(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	
	
	
	public BaseDaoImpl(){
		ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
		Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
		entityClass= (Class<T>) actualTypeArguments[0];
	}
	
	
	@Override
	public void save(T t) {
		this.getHibernateTemplate().save(t);
		
	}

	@Override
	public void delete(T t) {
		this.getHibernateTemplate().delete(t);
	}

	@Override
	public void update(T t) {
		this.getHibernateTemplate().update(t);
	}

	@Override
	public T findById(Serializable id) {
		
		return this.getHibernateTemplate().get(entityClass, id);
	}

	@Override
	public List<T> findAll() {
		String hql="from "+entityClass.getSimpleName();
		
		return this.getHibernateTemplate().find(hql);
	}



	@Override
	public void executeUpdate(String queryName, Object... objects) {
		Session session=this.getSession();
		
			Query query=session.getNamedQuery(queryName);
			
			int i=0;
			for(Object arg: objects){
				query.setParameter(i++, arg);
				
			}
			query.executeUpdate();
	}

	@Override
	public void pageQuery(PageBean pageBean) {
		int currentPage = pageBean.getCurrentPage();
		int pageSize = pageBean.getPageSize();
		DetachedCriteria detachedCriteria = pageBean.getDetachedCriteria();
		detachedCriteria.setProjection(Projections.rowCount());
		List<Long> list = this.getHibernateTemplate().findByCriteria(detachedCriteria);
	
		Long total = list.get(0);
		pageBean.setTotal(total.intValue());
		
		detachedCriteria.setProjection(null);
		
		detachedCriteria.setResultTransformer(DetachedCriteria.ROOT_ENTITY);
		int firstResult=(currentPage-1)*pageSize;
		int maxResult=pageSize;
		List rows=this.getHibernateTemplate().findByCriteria(detachedCriteria, firstResult, maxResult);
	
		pageBean.setRows(rows);
	}



	@Override
	public void saveOrUpdate(T entity) {
		this.getHibernateTemplate().saveOrUpdate(entity);
	}



	@Override
	public List<T> findByCriteria(DetachedCriteria detachedCriteria) {
		
		
		return this.getHibernateTemplate().findByCriteria(detachedCriteria);
	}

}
